$(function() {
	Finch.Wallet.init();
	Finch.Identification.init();

	var balancePlace = $('.js-balance-amount');
	var balanceSubamountPlace = $('.js-balance-subamount');
	var labelWallet = $('.menu__label-wallet');
	var labelBonus = $('.menu__label-bonus');
	var ticketsInput = $('[data-wallet]');

	var reloadWalletButton = $('.menu__refresh-button_wallet');
	var reloadBonusButton = $('.menu__refresh-button_bonus');
	var iconBonus = $('.ico_bonus');
	var iconRubWallet = $('.ico_rub--wallet');
	var iconRubSubamount = $('.subamount-rub-icon');

	balanceSubamountPlace.hide();

	reloadWalletButton.on('click', function() {
		reloadWalletButton.show();
		reloadWalletButton.addClass('spin');
		Finch.Wallet.refresh();

		iconRubSubamount.hide();
	});

	reloadBonusButton.on('click', function() {
		reloadBonusButton.show();
		reloadBonusButton.addClass('spin');
		Finch.Bonus.refresh();
	});

	Finch.Wallet.subscribe(function(status, balance) {
		if (status == 'ok') {
			reloadWalletButton.hide();
			iconRubWallet.show();
			ticketsInput.size() ? ticketsInput.attr('data-wallet', balance.amount) : '';
			balancePlace.text(balance.amount);
			if (balance.subAmount > 0) {
				balanceSubamountPlace.html('+' + balance.subAmount);
				iconRubSubamount.show();
				balanceSubamountPlace.show();
			}
		} else {
			reloadWalletButton.removeClass('spin');
			labelWallet.text('Недоступен');
			iconRubWallet.hide();
		}
	});

	var bonusPlace = $('.js-bonus-balance');
	if (bonusPlace.length > 0) {
		Finch.Bonus.init();
		Finch.Bonus.subscribe(function(status, amount) {
			if (status == 'ok') {
				iconBonus.show();
				reloadBonusButton.hide();
				bonusPlace.text(Math.floor(amount));
			} else {
				reloadBonusButton.removeClass('spin');
				labelBonus.text('Недоступны');
				iconBonus.hide();
			}
		});
	}

	var games = [
		{
			gameSelector: $('.games__item_4x20 .games__time'),
			dateSelector: $('#4x20_date'),
		},
		{
			gameSelector: $('.games__item_6x45 .games__time'),
			dateSelector: $('#6x45_date'),
		},
		{
			gameSelector: $('.games__item_5x36 .games__time'),
			dateSelector: $('#5x36_date'),
		},
		{
			gameSelector: $('.games__item_5x36plus .games__time'),
			dateSelector: $('#5x36plus_date'),
		},
		{
			gameSelector: $('.games__item_gzhl .games__time'),
			dateSelector: $('#gzhl_date'),
		},
		{
			gameSelector: $('.games__item_ruslotto .games__time'),
			dateSelector: $('#ruslotto_date'),
		},
		{
			gameSelector: $('.games__item_7x49 .games__time'),
			dateSelector: $('#7x49_date'),
		},
		{
			gameSelector: $('.games__item_zp .games__time'),
			dateSelector: $('#zp_date'),
		},
		{
			gameSelector: $('.games__item_6x36 .games__time'),
			dateSelector: $('#6x36_date'),
		},
		{
			gameSelector: $('.games__time.quick_top3'),
			dateSelector: $('#top3_date'),
		},
		{
			gameSelector: $('.games__time.quick_rapido'),
			dateSelector: $('#rapido_date'),
		},
		{
			gameSelector: $('.games__time.quick_rapido2'),
			dateSelector: $('#rapido2_date'),
		},
		{
			gameSelector: $('.games__time.quick_keno'),
			dateSelector: $('#keno_date'),
		},
		{
			gameSelector: $('.games__item_12x24 .games__time'),
			dateSelector: $('#12x24_date'),
		},
		{
			gameSelector: $('.games__time.quick_duel'),
			dateSelector: $('#duel_date'),
		},
		{
			gameSelector: $('.games__time.quick_talon'),
			dateSelector: $('#talon_date'),
		},
		{
			gameSelector: $('.games__item_5x50 .games__time'),
			dateSelector: $('#5x50_date'),
		},
		{
			gameSelector: $('.games__item_joker .games__time'),
			dateSelector: $('#joker_date'),
		},
		{
			gameSelector: $('.games__item_zodiac .games__time'),
			dateSelector: $('#zodiac_date'),
		},
		{
			gameSelector: $('.games__item_bingo75 .games__time'),
			dateSelector: $('#bingo75_date'),
		},
	];

	function setTimeHandler(game) {
		var gameSelector = game.gameSelector;
		var dateSelector = game.dateSelector;

		var distance = parseInt(dateSelector.html());
		distance = distance * 1000;
		var fastGames = [
			'#joker_date',
			'#rapido_date',
			'#rapido2_date',
			'#12x24_date',
			'#duel_date',
			'#top3_date',
			'#keno_date',
		];
		var x = setInterval(function() {
			distance = distance - 1000;

			var days = Math.floor(distance / (1000 * 60 * 60 * 24));
			var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
			var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
			var seconds = Math.floor((distance % (1000 * 60)) / 1000);
			var hourText = "00";
			var minuteText = "00";
			var secondsText = "00";

			if (hours < 10) {
				hourText = '0' + hours;
			} else hourText = '' + hours;
			if (minutes < 10) {
				minuteText = '0' + minutes;
			} else minuteText = '' + minutes
			if (seconds < 10) {
				secondsText = '0' + seconds;
			} else secondsText = '' + seconds
			
			var dayName = setDays(['день', 'дня', 'дней'])(days);
			if (distance > 86400000) {
				gameSelector.html('через ' + days + ' ' + dayName);
			} else if (distance <= 0) {
				var gameName = dateSelector
					.attr('id')
					.slice(0, dateSelector.attr('id').indexOf('_'));
				$.ajax({
					type: 'GET',
					url: '/fastgames/info/game-draw-time?game=' + gameName,
				}).done(function(data) {
					if (data.remainingSeconds > 0 && data.status == 'ok') {
						distance = data.remainingSeconds * 1000;
					}
				});
				gameSelector.html('сейчас');
			} else {
				var isFastGame = false;
				for (var i = 0; i <= fastGames.length; i++) {
					if (fastGames[i] == dateSelector.selector) {
						isFastGame = true;
					}
				}

				if (isFastGame) {
					gameSelector.html('через ' + (hours > 0 ? hourText + ":" : "") + minuteText + ':' + secondsText);
				} else {
					gameSelector.html('через ' + hourText + ':' + minuteText + ':' + secondsText);
				}
			}
		}, 1000);
	}

	$.each(games, function(i, game) {
		setTimeHandler(game);
	});
});

function setDays(titles) {
	var number = Math.abs(parseInt(number));
	var cases = [2, 0, 1, 1, 1, 2];
	return function(number) {
		return titles[
			number % 100 > 4 && number % 100 < 20 ? 2 : cases[number % 10 < 5 ? number % 10 : 5]
		];
	};
}

var resizeArray = [];

function resizeCouponsNum(tab) {
	var sumW = 0;
	var numW = 0;
	if (tab == 1) {
		resizeArray = [];
	}
	if (resizeArray.length > 0) {
		for (var i = 0; i < resizeArray.length; i++) {
			var obj = resizeArray[i];
			sumW += $(obj).width();
		}
	} else {
		for (var i = 0; i < $('.coupons-list .coupons__num').length; i++) {
			var obj = $('.coupons-list .coupons__num').eq(i);
			var widthObj = $(obj).width();
			if (widthObj > 40) {
				sumW += $(obj).width();
				resizeArray.push(obj);
			}
		}

		for (var i = 0; i < resizeArray.length; i++) {
			var obj = resizeArray[i];
			var h = Math.round(sumW / resizeArray.length);
			$(obj).height(h);
			$(obj).css('line-height', h + 'px');
		}
	}
}

$(function() {
	setTimeout(function() {
		resizeCouponsNum(0);
	}, 300);
});

function getScrollBarWidth() {
	var inner = document.createElement('p');
	inner.style.width = '100%';
	inner.style.height = '200px';
	var outer = document.createElement('div');
	outer.style.position = 'absolute';
	outer.style.top = '0px';
	outer.style.left = '0px';
	outer.style.visibility = 'hidden';
	outer.style.width = '200px';
	outer.style.height = '150px';
	outer.style.overflow = 'hidden';
	outer.appendChild(inner);
	document.body.appendChild(outer);
	var w1 = inner.offsetWidth;
	outer.style.overflow = 'scroll';
	var w2 = inner.offsetWidth;
	if (w1 == w2) w2 = outer.clientWidth;
	document.body.removeChild(outer);
	return w1 - w2;
}

var Popup = {
	popupOpenButton: $('.js-popup'),
	popupCloseButton: $('.popup__close, .popup__bg'),
	init: function() {
		this.popupOpenButton.click(function(e) {
			e.preventDefault();
			Popup.show($(this).data('popup'));
		});
		this.popupCloseButton.click(function() {
			Popup.close();
		});
	},
	show: function(id, callback) {
		$('body').addClass('popup-open');
		$('body').css('margin-right', getScrollBarWidth());
		var popup = $('.popup_' + id);
		this.element = popup;
		this.closeButton = $('.popup__close', popup);
		if (callback != undefined) {
			callback(popup);
		}
		popup.addClass('popup_active');
		return this;
	},
	close: function() {
		$('body').removeClass('popup-open');
		$('.popup').removeClass('popup_active');
	},
};
Popup.init();

$(function() {
	$('.header__burger, .layout__blocker, .top-nav-menu__burger').on(
		'click touchstart',
		function() {
			$('body').toggleClass('nav-open-start');
			$('body').toggleClass('nav-open');
			return false;
		}
	);
});

var minSpeed = 200;

// ==========================
// carousels
// ==========================
$(function() {
	// http://flickity.metafizzy.co/
	var $carousel = $('.header-slider').flickity({
		cellAlign: 'left',
		autoPlay: 5000,
		setGallerySize: false,
		wrapAround: true,
		//show/remove dots
		pageDots: true,
	});
	var flkty = $carousel.data('flickity');

	$carousel.on('settle.flickity', function() {
		$carousel.flickity('playPlayer');
	});

	$carousel.on();
	// http://flickity.metafizzy.co/
	$('.breadcrumbs_active .breadcrumbs__list').flickity({
		cellAlign: 'left',
		contain: true,
		rightToLeft: true,
		pageDots: false,
		arrowShape: '',
	});
});

// ==========================
// positions
// ==========================
$(function() {
	// sticky top panel
	var stickyNavTop = $('.main').offset().top;

	var stickyNav = function() {
		var scrollTop = $(window).scrollTop();

		if (scrollTop > stickyNavTop) {
			$('.top').addClass('top_active');
		} else {
			$('.top').removeClass('top_active');
		}
	};

	stickyNav();

	$(window).scroll(function() {
		stickyNav();
	});

	// animate scroll
	// *** scroll changed to more specific one
	// $('.top').each(function(){
	// 	$(this).click(function(){
	// 		$('html,body').animate({ scrollTop: 0 }, 300);
	// 		return false;
	// 	});
	// });
	$('.top-nav-menu__item--scroll-arrow')
		.find('.ico_arrow_top')
		.click(function() {
			$('html,body').animate({ scrollTop: 0 }, 300);
			return false;
		});
	$('.pseudo').click(function() {
		$('html, body').animate(
			{
				scrollTop: ($($.attr(this, 'href')).offset().top += -60),
			},
			300
		);
		return false;
	});
});

// ==========================
// actions
// ==========================
$(function() {
	$(document).bind('dragstart', function() {
		return false;
	});

	// fake login
	$('.header__wallet').on('click', function() {
		$(this)
			.hide()
			.siblings()
			.show();
	});

	$('.search__open').click(function() {
		$('.title_search').addClass('title_search_active');
		setTimeout(function() {
			$('.search__input').focus();
		}, 500);
	});
	$('.search__close').click(function() {
		$('.title_search').removeClass('title_search_active');
	});

	var combi = 'check-combi';
	$('.buttons-set_tabs').on('click', '.buttons-set__button', function(e) {
		var tabItem = $(this);
		e.preventDefault();
		location.hash = tabItem.data('tabs');
		if (tabItem.hasClass('buttons-set__button_active')) {
			$('[data-tabs-content=' + tabItem.data('tabs') + ']').slideUp(minSpeed);
			$(this).removeClass('buttons-set__button_active');
		} else {
			$('[data-tabs-content=' + tabItem.data('tabs') + ']')
				.slideDown(minSpeed)
				.siblings('[data-tabs-content]')
				.slideUp(minSpeed);
			$(this)
				.addClass('buttons-set__button_active')
				.siblings()
				.removeClass('buttons-set__button_active');

			if ($(this).attr('data-tabs') == 'check-combi') {
				setTimeout(function() {
					resizeCouponsNum(0);
				}, 300);
			}
		}
	});
	if (location.hash === '#' + combi) {
		$('.buttons-set__button')
			.filter(function(i, el) {
				return $(el).data('tabs') === 'check-combi';
			})
			.trigger('click');
	}

	// tabs selector
	$('.js-select').on('change', function() {
		var selectItem = $(this);
		$('.coupons_' + selectItem.find(':selected').data('game'))
			.slideDown(minSpeed)
			.siblings()
			.slideUp(minSpeed);
	});

	// news accordeon
	$('.news_archive').on('click', '.news__month', function() {
		var newsPeriod = $(this);
		//newsPeriod.parent().siblings().removeClass('news__period_active').find('.news__list').slideUp(minSpeed);
		if (newsPeriod.parent().hasClass('news__period_active')) {
			newsPeriod.next().slideUp(minSpeed);
			newsPeriod.parent().removeClass('news__period_active');
		} else {
			newsPeriod.next().slideDown(minSpeed);
			newsPeriod.parent().addClass('news__period_active');
		}
	});

	// change search button
	$('.search__input').on('keyup', function() {
		$('.search__button').prop('disabled', this.value == '' ? true : false);
	});

	// phone validator
	$('#phone').mask('(999) 999-99-99');

	// show password
	$('.input__status').on('click', function() {
		$(this)
			.parent()
			.parent()
			.toggleClass('input_show-password');
		$('#regPassword').hideShowPassword('toggle');
	});

	$('.history')
		.on('click', '.history__delete', function() {
			$(this)
				.parents('.history__item')
				.remove();
			$('.history__section')
				.not(':has(.history__item)')
				.remove();
		})
		.on('click', '.history__clear', function() {
			var url;
			$('.history__section').remove();
			if (this.dataset.info) url = JSON.parse(this.dataset.info).url;
			new AsyncHandler(
				1000,
				url,
				{},
				'POST',
				function() {},
				function() {},
				function() {}
			).start();
		});
});

function getUserAgent() {
	var ua = navigator.userAgent;
	var match = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d*)/i) || [];
	var tmp;

	if (/trident/i.test(match[1])) {
	  tmp = /\brv[ :]+(\d+)/g.exec(ua) || [];
	  return 'IE/'+(tmp[1] || '');
	}

	if (match[1] === 'Chrome') {
	  tmp = ua.match(/\b(OPR|Edge)\/(\d+)/);
	  if (tmp != null) {
	    return tmp[1] + '/' +tmp[2];
	  }
	}

	match = match[2] ? [match[1], match[2]] : [navigator.appName, navigator.appVersion, '-?'];

	if ((tmp = ua.match(/version\/(\d+)/i)) != null) {
	  match.splice(1, 1, tmp[1]);
	}

	return match[0] + '/' + match[1];
}

ga(function(tracker) {
	window.GAclientId = tracker.get('clientId');
	window.GAtrackingId = tracker.get('trackingId');
	console.log('check!!', window.GAclientId, window.GAtrackingId);
});

function withGAdata(callback) {
	function setData(dataObject) {
        dataObject.clientId = GAclientId;
        dataObject.trackingId = GAtrackingId;
        dataObject.userAgent = getUserAgent();
	}
	callback(setData)
}

/*
(function() {
	ECommerceGame = function(value) {
		value = value || {
			ecommerce: {
				purchase: {},
			},
		};

		return {
			flatMap: function(f) {
				return f(value);
			},
			map: function(f) {
				return ECommerceGame.of(f(value));
			},
			getRandom: function(from, to) {
				return Math.random() + (Math.random() * (to - from) + from);
			},
			generateID: function(groups, id) {
				id = id || '';

				if (groups) {
					var randomFrom = this.getRandom(64, 256) * 879437;
					var randomTo = this.getRandom(384, 768) * 99898954;
					var randomGroup = Math.floor(this.getRandom(randomFrom, randomTo))
						.toString(16)
						.toUpperCase();
					var nextId = id ? id + '-' + randomGroup : randomGroup;

					return this.generateID(groups - 1, nextId);
				} else {
					return id;
				}
			},
			getTopThreeType: function(type) {
				switch (type) {
					case 1:
						return 'tochno1';
					case 2:
						return 'lyubye2';
					case 4:
						return 'tochno3';
					case 5:
						return 'pervye2';
					case 6:
						return 'poslednie2';
					case 7:
						return 'lyubye3';
					case 8:
						return 'tochno3lyubye3';
					case 9:
						return 'kombo';
					default:
						return undefined;
				}
			},
			setCurrency: function(currency) {
				return this.map(
					function(value) {
						return Object.assign({}, value, {
							ecommerce: Object.assign({}, value.ecommerce, {
								currencyCode: currency,
							}),
						});
					}.bind(this)
				);
			},
			configureActionField: function(totalSum, origin, gamesQuantity) {
				return this.map(
					function(value) {
						var actionField = {
							id: this.generateID(5),
							revenue: totalSum,
							affiliation: origin,
							metric4: gamesQuantity,
							list: window.location.search.split('bm=')[1] || '',
						};

						return Object.assign({}, value, {
							ecommerce: Object.assign({}, value.ecommerce, {
								purchase: Object.assign({}, value.ecommerce.purchase, {
									actionField: value.ecommerce.purchase.actionField
										? Object.assign({}, value.ecommerce.purchase.actionField, {
												actionField: actionField,
										  })
										: actionField,
								}),
							}),
						});
					}.bind(this)
				);
			},
			addProduct: function(
				id,
				name,
				jackpot,
				price,
				drawsQuantity,
				multiplier,
				ticketsQuantity,
				currentUser,
				fillMode,
				postpone,
				favouriteNumbers,
				combinationsQuantity,
				gift,
				type
			) {
				jackpot = jackpot || '';
				postpone = postpone || 'postpone_draw_no';
				favouriteNumbers = favouriteNumbers || 'no';
				combinationsQuantity = combinationsQuantity || 1;
				gift = gift || false;
				type = this.getTopThreeType(type) || false;

				if (currentUser) {
					if (currentUser.vip) {
						currentUser = 'vip';
					} else {
						currentUser = 'user';
					}
				} else {
					currentUser = 'empty';
				}

				return this.map(
					function(value) {
						var product = {
							id: id,
							name: name,
							price: price,
							quantity: combinationsQuantity,
							metric1: drawsQuantity || 1,
							metric2: multiplier,
							metric3: ticketsQuantity,
							dimension4: currentUser,
							variant: fillMode,
							dimension5: type || postpone,
							category: gift ? 'gift' : 'classic',
							dimension7: favouriteNumbers,
							coupon: jackpot,
							brand: '',
						};

						return Object.assign({}, value, {
							ecommerce: Object.assign({}, value.ecommerce, {
								purchase: Object.assign({}, value.ecommerce.purchase, {
									products: value.ecommerce.purchase.products
										? value.ecommerce.purchase.products.concat(product)
										: [product],
								}),
							}),
						});
					}.bind(this)
				);
			},
			addGTMData: function() {
				return this.map(function(value) {
					return Object.assign({}, value, {
						ecommerce: Object.assign({}, value.ecommerce),
						event: 'gtm-ecom-event',
						'gtm-eventAction': 'ProductPurchase',
						'gtm-eventCategory': 'Ecommerce',
						'gtm-eventLabel': 'purch',
						'gtm-non-interaction': 'False',
						'gtm.uniqueEventId': 2,
					});
				});
			},
		};
	};

	ECommerceGame.of = ECommerceGame;
})(window);
*/
